import Vue from 'vue';
import Vuex from 'vuex';
import Request from '@/common/http/request.js'
import * as utils from '@/common/comFun/utils.js';
import TicketModule from './module/TICKET.js';
import QmsModule from './module/QMS.js';
import GuyueModule from './module/Guyue.js';
import {
	HubConnectionBuilder,
	LogLevel
} from '@/uni_modules/Lyuan-SignalR/js_sdk/signalr.js';
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		currentTimeString: '', // 初始时间
		timerId: null, // 用于存储定时器的ID  
		ModuleInfo_All: uni.getStorageSync('ModuleInfo_All') ? JSON.parse(uni.getStorageSync(
			'ModuleInfo_All')) : [], // 新 菜单模块数据信息
		Module_Tabbar: uni.getStorageSync('Module_Tabbar') ? JSON.parse(uni.getStorageSync(
			'Module_Tabbar')) : [], // 新 提取的底部栏数据

		FCJType: null, // 公司报工类型
		BaseScreenParm: {}, // 记录跳转到筛选页面，需要的参数

		Authorization: false, // 授权
		CreateTime: null, // 授权日期
		expireDate: null, // 授权期限
		UserInfo: uni.getStorageSync('UserInfo') ? JSON.parse(uni.getStorageSync('UserInfo')) : {},
		APPModules: {},
		UpdateSwitch: false, // 开启检索更新后，无更新时是否提示。
		sysDeviceInfo: !utils.isEmpty(uni.getStorageSync('sysDeviceInfo')) ? JSON.parse(uni.getStorageSync(
			'sysDeviceInfo')) : {},


		connection: null,
		messages: [],

		SignalRConnect: null,
		IPModel: {
			// SignalR: '127.0.0.1', // SignalR
			SignalR_Status: false, // 连接状态
			SignalR_StatusInfo: {}, // 连接状态
		},
		SignalRClientID: null,
		SignalRLiveMethod: '',
		hasMsg: false, // 判断是否有新的消息

		openMsgBtnType: String(uni.getStorageSync('openMsgBtnType')) || 'true', // 全局消息按钮是否开启
		activeCtx: null, // 全局消息悬浮按钮实例对象
	},
	mutations: {
		/** 修改state 数据_测试
		 * 	payload.Name1 - state层级属性数据 如 user.info.score
		 * 	payload.data  - 赋值内容
		 *  payload.StorageName  - 缓存名称，有缓存时会开启缓存
		 *  payload.StorageData  - 缓存内容，已处理成JSON格式
		 * 	@param {object} payload  这是一个对象，包含属性名，赋值内容，缓存名、缓存内容
		 */
		ChangeAndSetStateData(state, payload) {
			// 解构出要修改的属性名
			const {
				Name1,
				data,
				StorageName,
				StorageData,
			} = payload;

			// 如果属性名存在多级，可以使用动态属性名来修改对应的值
			const levels = Name1.split('.');
			let currentState = state;
			for (let i = 0; i < levels.length - 1; i++) {
				currentState = currentState[levels[i]];
			}
			currentState[levels[levels.length - 1]] = data;

			// 根据StorageName参数来决定是否记录缓存
			if (StorageName) {
				uni.setStorageSync(StorageName, StorageData);
			}
		},
		AddSignalRLive(state, liveMethod) {
			if (state.SignalRLiveMethod) {
				clearInterval(state.SignalRLiveMethod);
			}
			state.SignalRLiveMethod = liveMethod;
			//state.SignalRLiveMethod();
		},

		SET_CONNECTION(state, connection) {
			state.connection = connection;
		},
		ADD_MESSAGE(state, message) {
			state.messages.push(message);
		},

		SET_CURRENT_TIME(state, timeString) {
			state.currentTimeString = timeString;
		},
		SET_TIMER_ID(state, timerId) {
			state.timerId = timerId;
		},
		CLEAR_TIMER_ID(state) {
			state.timerId = null;
		}
	},
	actions: {
		pushMsgByLocal() { // 本地发送，搭配signalR使用
			// #ifndef APP-IOS
			plus.push.createMessage("消息推送来了", null, {
				sound: 'system',
				delay: 1
			})

			// #endif


			// #ifdef APP-IOS


			// #endif
		},
		connect({
			commit,
			dispatch,
			state
		}, {
			urlBuilder
		}) {

			const connection = new HubConnectionBuilder()
				.withUrl(urlBuilder)
				.configureLogging(LogLevel.Trace)
				.build();

			// console.log(urlBuilder)

			commit('ChangeAndSetStateData', {
				Name1: 'SignalRConnect',
				data: connection
			});

			connection.onclose(() => {
				setTimeout(() => {
					dispatch('connect', {
						urlBuilder
					}); // 重新连接  
				}, 5000);
			});

			// try {
			// 发起连接
			connection.start().then(function() {
				// console.log(state.UserInfo.UserID)


				let SignalRKey = {
					oldKey: uni.getStorageSync('LocalMsgKey'),
					newKey: '',
				}

				// 参数：(连接字段，账套ID，机器码)
				let deviceID = uni.getStorageSync('Only_Identity');
				connection.invoke("ConnectByMachineNo", +state.UserInfo.Business, +state.UserInfo
						.UserID,
						deviceID)
					.catch(
						function(err) {
							console.log(err)
						});


				// 查看连接状态
				connection.on("onConnect", (data) => {
					let backData = JSON.parse(data);
					let connetType = false;
					if (backData.Status == 200) {
						connetType = true;

						SignalRKey.newKey = data.Data;
						// 记录signalR连接的kay
						uni.setStorageSync('LocalMsgKey', data.Data);
					} else if (backData.Status == 500) {
						connetType = false;
					}

					commit('ChangeAndSetStateData', {
						Name1: 'IPModel.SignalR_Status',
						data: connetType
					});

					commit('ChangeAndSetStateData', {
						Name1: 'SignalRClientID',
						data: data
					});



					// 接收数据
					connection.on("onReceiveMSG", (ret) => {
						let data = JSON.parse(ret)

						if (data.Status == 200) {
							//  提示接收到消息， 
							let theType = state.openMsgBtnType == 'true';
							commit('ChangeAndSetStateData', {
								Name1: 'hasMsg',
								data: theType
							});
							dispatch('pushMsgByLocal')
						}
					})
				});

			}).catch(function(err) {
				commit('ChangeAndSetStateData', {
					Name1: 'IPModel.SignalR_Status',
					data: false
				});
				//5s断线重连
				setTimeout(() => {
					dispatch('connect', {
						urlBuilder
					});
				}, 5000);

			});;



			// } catch (error) {
			// 	console.error('Failed to start connection:', error);
			// 	setTimeout(() => {
			// 		dispatch('connect', {
			// 			urlBuilder
			// 		}); // 重新连接  
			// 	}, 5000);
			// }
		},
		// disconnect({
		// 	commit,
		// 	state
		// }) {
		// 	if (state.connection && state.connection.state === signalR.HubConnectionState.Connected) {
		// 		state.connection.stop().catch(err => console.error(err.toString()));
		// 		commit('SET_CONNECTION', null);
		// 	}
		// },
		// sendMessage({
		// 	state
		// }, message) {
		// 	if (state.connection && state.connection.state === signalR.HubConnectionState.Connected) {
		// 		state.connection.invoke("SendMessage", message).catch(err => console.error(err.toString()));
		// 	}
		// },

		GetMessageInfo({
			commit,
			dispatch,
			state
		}) { // 获取消息详情
			return Request.PromiseRequest('GetSYSMessageList', {
				UserID: state.UserInfo.UserID
			}).promise;

		},

		startUpdatingTime({
			commit
		}) {
			const updateTime = () => {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hour = String(now.getHours()).padStart(2, '0');
				const minute = String(now.getMinutes()).padStart(2, '0');
				const second = String(now.getSeconds()).padStart(2, '0');
				const timeString = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
				commit('SET_CURRENT_TIME', timeString);
			};

			const timerId = setInterval(updateTime, 1000); // 每秒更新时间  
			commit('SET_TIMER_ID', timerId);
		},
		stopUpdatingTime({
			commit,
			state
		}) {
			if (state.timerId) {
				clearInterval(state.timerId);
				commit('CLEAR_TIMER_ID');
			}
		}
	},
	getters: {
		GetFCJType: state => { // 获取公司报工类型
			if (uni.getStorageSync('FCJType')) {
				return uni.getStorageSync('FCJType')
			} else {
				return state.FCJType
			}
		},
	},
	modules: { // 可以添加更多的模块
		QmsModule: QmsModule, // 将主题模块添加为名为"QmsModule"的模块
		TicketModule: TicketModule,
		GuyueModule: GuyueModule,
	}
})

export default store